<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-select
          v-model="form.dimensionality"
          placeholder="目标维度"
          class="!w-[160px]"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsTargetConfig']?.[0].dimensionalityText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.target_status"
          class="!w-[160px]"
          placeholder="状态"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsTargetConfig']?.[0].targetStatusText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.target_rule"
          class="!w-[160px]"
          placeholder="目标角色"
          clearable
        >
          <el-option
            v-for="item in options['goods.GoodsTargetConfig']?.[0].targetRuleText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-date-picker
          v-model="form.target_month"
          type="month"
          value-format="YYYY-MM-DD"
          placeholder="目标周期"
        />
        <!-- <el-input class="w-50" v-model="form.remark" placeholder="达成率"></el-input> -->
      </template>
      <template #toolbar_btns>
        <!-- <el-button type="primary" @click="open('add')"
          ><svg-icon icon-class="add_new" />新增</el-button
        > -->
        <VButton
          auth="/goods/basics/target-configuration/add"
          type="primary"
          @click="open('add')"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
        <VButton
          auth="/goods/basics/target-configuration/enable-disable"
          @click="handleStatus(0)"
          ><svg-icon icon-class="add_new" />启用</VButton
        >
        <VButton
          auth="/goods/basics/target-configuration/enable-disable"
          @click="handleStatus(1)"
          >禁用</VButton
        >
      </template>
    </VTable>
  </VPage>
  <ComModal ref="addref" @query="query"></ComModal>
  <finishDetail ref="finishDetailRef"></finishDetail>
</template>

<script setup lang="jsx" name="BasicsTarget-configuration">
import { ElMessage, ElMessageBox } from "element-plus";
import ComModal from "./components/ComModal.vue";
import { getOptions } from "@/api/index.js";
import { queryGoodsTargetConfigList, setStausGoodsTargetConfig } from "./api";
import finishDetail from "./components/finishDetail";
import { toRefs } from "vue";
const tableRef = ref();
const addref = ref(null);

const tableOptins = reactive({
  formConfig: {},
  rowConfig: {
    height: 50,
  },
  columns: [
    { type: "checkbox", width: "40", fixed: "left" },
    { type: "seq", field: "seq", title: "序号", width: 60 },
    {
      field: "id",
      title: "目标周期",
      minWidth: 190,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.month_start}至{row.month_end}
            </div>
          );
        },
      },
    },
    {
      field: "target_rule_text",
      title: "目标角色",
      width: 80,
    },
    {
      field: "dimensionality_text",
      title: "目标维度",
      width: 80,
    },
    {
      field: "target_type_text",
      title: "目标类型",
      minWidth: 80,
    },
    {
      field: "dimensionality",
      title: "总目标",
      width: 120,
      slots: {
        default: ({ row }) => {
          return computeTargetValue(row.goods_target_config_detail);
        },
      },
    },
    {
      field: "importer_company_name",
      title: "达成率",
      width: 80,
      slots: {
        default: ({ row }) => {
          return computeFinishRate(row.goods_target_config_detail);
        },
      },
    },
    {
      field: "score",
      title: "目标完成详情",
      width: 110,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button type="primary" link onClick={() => hanldeViewDetail(row)}>
                点击查看
              </el-button>
            </div>
          );
        },
      },
    },
    {
      field: "target_status_text",
      title: "状态",
      width: 80,
    },
    {
      field: "remark",
      title: "备注",
      showOverflow: "title",
      slots: {
        default: ({ row }) => {
          return <div class="overflow-ellipsis overflow-hidden">{row.remark}</div>;
        },
      },
      minWidth: 160,
    },
    { field: "created_user_text", title: "创建人", width: 160 },
    { field: "created_at", title: "创建时间", width: 180 },
    {
      title: "操作",
      fixed: "right",
      width: 100,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex justify-center">
              <VButton
                auth="/goods/basics/target-configuration/edit"
                type="primary"
                link
                onClick={() => open("edit", row)}
              >
                编辑
              </VButton>
              <VButton
                auth="/goods/basics/target-configuration/add"
                type="primary"
                link
                onClick={() => open("copy", row)}
              >
                复制
              </VButton>
            </div>
          );
        },
      },
    },
  ],

  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => queryGoodsTargetConfigList({ ...form, ...page }),
    },
  },
});
// 列表数据

const query = () => {
  tableRef?.value.query();
};

const data = reactive({
  options: {
    typeList: [],
  },
});
const { options } = toRefs(data);

const fetchOption = async () => {
  getOptions({
    version: "v1",
    name: ["goods.GoodsTargetConfig"],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

const open = (type, row) => {
  nextTick(() => {
    addref.value.open(type, row);
  });
};

const logRef = ref();
const showLog = (id) => {
  logRef.value.open(id);
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

// 切换状态
const handleStatus = async (status) => {
  const records = getSelectRow().map((i) => i.id);
  if (!isHandle()) return;

  await setStausGoodsTargetConfig({
    ids: records,
    status,
  });
  ElMessage.success("操作成功");
  query();
};

// 查看详情
const finishDetailRef = ref();
const hanldeViewDetail = (row) => {
  nextTick(() => {
    finishDetailRef.value.open(row);
  });
};

// 计算达成率
const computeFinishRate = (list) => {
  if (list.length == 0) {
    return "--";
  }
  const totalFinishValue = list.reduce((sum, item) => sum + Number(item.finish_value), 0);
  const totalTargetValue = list.reduce((sum, item) => sum + Number(item.target_value), 0);

  if (totalTargetValue === 0) {
    return 0; // 避免除以零的情况
  }

  return ((totalFinishValue / totalTargetValue) * 100).toFixed(2) + "%";
};

// 计算总目标
const computeTargetValue = (list) => {
  if (list.length == 0) {
    return "--";
  }
  const totalTargetValue = list.reduce((sum, item) => sum + Number(item.target_value), 0);
  return parseFloat(totalTargetValue.toFixed(2));
};
</script>
